import os
import librosa
import numpy as np
from sklearn.decomposition import PCA, FastICA
from scipy.io import wavfile

"""
This script is to preprocess the speech signal data of patients with depression.
created by JINJing
"""

# 设置音频文件所在的目录和输出目录
audio_dir = 'path_to_audio_files'
output_dir = 'path_to_output_dir'

# 设置目标采样率
target_sr = 16000

# 初始化PCA和ICA对象
pca = PCA(n_components=10)  # 假设我们想要降维到10个主成分
ica = FastICA(n_components=10)  # 假设我们想要提取10个独立成分

# 遍历目录中的所有音频文件
for filename in os.listdir(audio_dir):
    if filename.endswith('.wav'):
        filepath = os.path.join(audio_dir, filename)

        # 读取音频文件
        y, sr = librosa.load(filepath, sr=target_sr)

        # 提取特征，这里以MFCC为例
        mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)  # 假设提取40个MFCC系数

        # 将MFCC系数展平
        mfccs_flat = mfccs.flatten()

        # 使用PCA进行降维
        mfccs_pca = pca.fit_transform(mfccs_flat.reshape(1, -1))

        # 使用ICA进行降维
        mfccs_ica = ica.fit_transform(mfccs_flat.reshape(1, -1))

        # 保存PCA和ICA结果到CSV文件
        output_file_pca = os.path.join(output_dir, f'{filename.replace(".wav", "")}_mfccs_pca.csv')
        output_file_ica = os.path.join(output_dir, f'{filename.replace(".wav", "")}_mfccs_ica.csv')

        np.savetxt(output_file_pca, mfccs_pca, delimiter=',')
        np.savetxt(output_file_ica, mfccs_ica, delimiter=',')

        print(f"Processed {filename} and saved PCA and ICA results.")